<template>
  <div class="category-view">
    <Header />
    
    <div class="cart-container">
      <div class="cart-header">
        <h1>购物车</h1>
        <p>您已选择 {{ cartItems.length }} 件商品</p>
      </div>
      
      <div class="cart-content">
        <div class="cart-items" v-if="cartItems.length > 0">
          <div 
            v-for="item in cartItems" 
            :key="item.id" 
            class="cart-item"
          >
            <div class="item-image">
              <img :src="item.image" :alt="item.title" />
            </div>
            
            <div class="item-info">
              <h3 class="item-title">{{ item.title }}</h3>
              <p class="item-description">{{ item.description }}</p>
              <p class="item-category">{{ item.category }}</p>
            </div>
            
            <div class="item-price">
              ￥{{ item.price.toLocaleString() }}
            </div>
            
            <div class="item-actions">
              <el-button 
                type="danger" 
                size="small" 
                :icon="Delete" 
                @click="removeItem(item.id)"
              >
                删除
              </el-button>
            </div>
          </div>
        </div>
        
        <div class="empty-cart" v-else>
          <el-empty description="购物车空空如也">
            <el-button type="primary" @click="goShopping">
              去购物
            </el-button>
          </el-empty>
        </div>
        
        <div class="cart-summary" v-if="cartItems.length > 0">
          <div class="summary-card">
            <h3>订单摘要</h3>
            
            <div class="summary-item">
              <span>商品数量:</span>
              <span>{{ totalQuantity }} 件</span>
            </div>
            
            <div class="summary-item">
              <span>商品总价:</span>
              <span>￥{{ totalPrice.toLocaleString() }}</span>
            </div>
            
            <div class="summary-item">
              <span>配送费用:</span>
              <span>￥{{ shippingFee.toLocaleString() }}</span>
            </div>
            
            <el-divider />
            
            <div class="summary-total">
              <span>应付总额:</span>
              <span class="total-amount">￥{{ (totalPrice + shippingFee).toLocaleString() }}</span>
            </div>
            
            <el-button 
              type="primary" 
              size="large" 
              class="checkout-btn"
              @click="handleCheckout"
            >
              立即结算
            </el-button>
          </div>
        </div>
      </div>
    </div>
    
    <Footer />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import Header from '@/components/Header.vue'
import Footer from '@/components/Footer.vue'
import { getCartItems, deleteCartItem } from '@/api/cart.js'
import { createOrder } from '@/api/order'

const router = useRouter()

// 购物车数据
const cartItems = ref([])
const shippingFee = ref(15)
const loading = ref(false)

// 获取购物车列表
const fetchCartItems = async () => {
  loading.value = true
  try {
    const response = await getCartItems()
    
    // 处理后端返回的标准格式响应
    if (response && response.code === 200) {
      // 转换后端返回的购物车项数据为前端期望的商品格式
      cartItems.value = response.data.items.map(item => ({
        id: item.id, // 购物车项ID
        title: item.product_name, // 商品名称
        price: item.product_price, // 商品价格
        // 处理商品图片路径，确保能正确显示
        image: processImageUrl(item.product_image),
        description: '', // 描述字段后端未提供，留空
        category: '' // 分类字段后端未提供，留空
      }))
    } else if (Array.isArray(response)) {
      // 兼容旧格式
      cartItems.value = response
    } else {
      cartItems.value = []
    }
  } catch (err) {
    console.error('获取购物车失败:', err)
    ElMessage.error('获取购物车失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 处理图片URL的函数，确保图片能正确显示
const processImageUrl = (image) => {
  // 如果没有图片，返回默认占位图
  if (!image) {
    return 'https://via.placeholder.com/120x120?text=No+Image';
  }
  
  // 如果图片是对象类型，尝试获取其中的image属性
  if (typeof image === 'object' && image !== null) {
    image = image.image || image;
  }
  
  // 如果图片是字符串，检查是否为完整URL
  if (typeof image === 'string') {
    // 如果图片路径以http开头，直接返回
    if (image.startsWith('http://') || image.startsWith('https://')) {
      return image;
    }
    // 如果是相对路径，添加基础URL
    if (image.startsWith('/')) {
      return `http://127.0.0.1:8000${image}`;
    }
    // 如果是相对路径（不以/开头），添加基础URL和/images前缀
    return `http://127.0.0.1:8000/images/${image}`;
  }
  
  // 其他情况返回默认占位图
  return 'https://via.placeholder.com/120x120?text=No+Image';
}

const totalQuantity = computed(() => {
  return cartItems.value.length
})

const totalPrice = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.price, 0)
})

const removeItem = async (itemId) => {
  ElMessageBox.confirm('确定要删除这件商品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteCartItem(itemId)
      
      if (response && response.code === 200) {
        cartItems.value = cartItems.value.filter(item => item.id !== itemId)
        ElMessage.success('商品删除成功')
      } else {
        ElMessage.error('删除商品失败')
      }
    } catch (err) {
      console.error('删除购物车商品失败:', err)
      ElMessage.error('删除商品失败，请稍后重试')
    }
  })
}

const handleCheckout = async () => {
  if (cartItems.value.length === 0) {
    ElMessage.warning('购物车为空，无法结算')
    return
  }

  try {
    // 弹出收货地址输入框
    const { value: shippingAddress } = await ElMessageBox.prompt(
      '请输入收货地址',
      '结算确认',
      {
        confirmButtonText: '确认结算',
        cancelButtonText: '取消',
        inputPattern: /^.+$/, // 非空验证
        inputErrorMessage: '收货地址不能为空'
      }
    )

    if (shippingAddress) {
      // 创建订单
      const response = await createOrder({ shipping_address: shippingAddress })
      
      if (response && response.code === 200) {
        // 清空购物车
        cartItems.value = []
        ElMessage.success('订单创建成功！商品已设为已售状态')
        
        // 可选：跳转到订单页面
        // router.push('/profile?tab=orders')
      } else {
        ElMessage.error('订单创建失败：' + (response.message || '未知错误'))
      }
    }
  } catch (err) {
    if (err !== 'cancel') { // 用户点击取消时不报错
      console.error('结算失败:', err)
      ElMessage.error('结算失败，请稍后重试：' + (err.response?.data?.detail || err.message))
    }
  }
}

const goShopping = () => {
  router.push('/')
}

// 组件挂载时获取购物车数据
onMounted(() => {
  fetchCartItems()
})
</script>

<style scoped>
.category-view {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.cart-container {
  flex: 1;
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.cart-header {
  text-align: center;
  margin-bottom: 40px;
}

.cart-header h1 {
  color: #333;
  margin-bottom: 10px;
}

.cart-header p {
  color: #666;
  margin: 0;
}

.cart-content {
  display: grid;
  grid-template-columns: 1fr 350px;
  gap: 30px;
}

.cart-items {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.cart-item {
  display: grid;
  grid-template-columns: 80px 1fr 100px 100px ;
  gap: 20px;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s;
}

.cart-item:hover {
  transform: translateY(-2px);
}

.item-image img {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 8px;
}

.item-title {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.item-description {
  margin: 0 0 4px 0;
  color: #666;
  font-size: 14px;
}

.item-category {
  margin: 0;
  color: #999;
  font-size: 12px;
}

.item-price,
.item-total {
  font-weight: 600;
  color: #e74c3c;
  font-size: 16px;
}

.empty-cart {
  grid-column: 1 / -1;
  text-align: center;
  padding: 60px 0;
}

.cart-summary {
  height: fit-content;
}

.summary-card {
  background: white;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.summary-card h3 {
  margin: 0 0 20px 0;
  color: #333;
  text-align: center;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  color: #666;
}

.summary-total {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 20px 0;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.total-amount {
  font-size: 20px;
  font-weight: bold;
  color: #e74c3c;
}

.checkout-btn {
  width: 100%;
  height: 48px;
  font-size: 16px;
}
</style>